package com.topone.controller.aspect;

import static com.topone.Const.Model.*;

import com.topone.Exception.FanZoneException;
import com.topone.Utils.wx.builder.template.WxTemplateMessageService.WxTemplateDataBuilder;
import com.topone.dataObject.TcUser;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.util.Objects;


@Component
@Aspect
public class TcUserAspect extends BaseAspect {
    //

    @Before(value = "execution(* com.topone.controller.SmsController.sms(..))")
    public void processBefore(JoinPoint joinPoint) {
            this.executeProcessBefore(joinPoint);
    }

    private void executeProcessBefore(JoinPoint joinPoint) {
        LOG.debug("---------------------------------------JoinAllAspect() is running!");
        LOG.debug("hijacked : " + joinPoint.getSignature().getName());
        Object[] objects = joinPoint.getArgs();
        String mobile = (String) objects[0];
        String openid = (String) objects[1];
        if (StringUtils.isEmpty(mobile)) {
            throw new FanZoneException(5000, "手机号不能为空");
        }
        if (StringUtils.isEmpty(openid)) {
            throw new FanZoneException(5000, "openid不能为空");
        }
        if (Objects.nonNull(userService.findByPhone(mobile))) {
            throw new FanZoneException(5000, "手机号码已使用");
        }
        TcUser tcUser = userService.findByopenid(openid);
        if (Objects.isNull(tcUser)) {
            throw new FanZoneException(5000, "用户不存在");
        }
        updatePhoneMessage(tcUser);
    }


    public void updatePhoneMessage(TcUser tcUser) {
        WxTemplateDataBuilder builder = wxTemplateMessageService.getSubmitMessageBuilder(UPDATE_PHONE);
        if (builder != null) {
            WxMpTemplateMessage message = builder.build(tcUser);
            message.setToUser(tcUser.getOpenid());
            message.setUrl("");
            sendTemplateMessage(message);
        } else {
            LOG.warn("No message builder is found: ");
        }
    }
}
